﻿using BZ.Logger;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace NDK.Module.Model
{
    public delegate byte[] ReceiveEvent(List<byte> RcvBytes);
    public class MServer
    {
        public int Port = 50000;
        public const string DnsStr = "192.168.3.25";//"localhost" Pre
        //public const string DnsStr = "192.168.3.29";//"localhost" Post
        IPAddress Iaddress = null;
        IPEndPoint LocalIpPort = null;

        public Socket Socket1;
        Thread ThreadWatch;
        ReceiveEvent cRcvEvent = null;
        public MServer(string LocalIpStr, string LocalPort, ReceiveEvent tRcvEvent)
        {
            try
            {
                if (string.IsNullOrEmpty(LocalIpStr))
                    return;
                Port = Convert.ToInt32(LocalPort);
                cRcvEvent = tRcvEvent;
                string[] ipstrs = LocalIpStr.Split('.');
                bool isset = false;
                if (ipstrs != null && ipstrs.Length >= 4)
                {
                    byte[] ipbytes = new byte[4];
                    ipbytes[0] = Convert.ToByte(Convert.ToInt32(ipstrs[0]));
                    ipbytes[1] = Convert.ToByte(Convert.ToInt32(ipstrs[1]));
                    ipbytes[2] = Convert.ToByte(Convert.ToInt32(ipstrs[2]));
                    ipbytes[3] = Convert.ToByte(Convert.ToInt32(ipstrs[3]));
                    IPAddress IaddressClient = new IPAddress(ipbytes);
                    if (IaddressClient != null)
                    {
                        LocalIpPort = new IPEndPoint(IaddressClient, Port);
                        isset = true;
                    }
                }
                if (!isset)
                {
                    Iaddress = Dns.GetHostEntry(DnsStr).AddressList[0];
                    LocalIpPort = new IPEndPoint(Iaddress, Port);
                }
                TListient();
            }
            catch { }
        }
        public void Close()
        {
            try
            {
                if (ThreadWatch != null)
                    ThreadWatch.Abort();
                if (Socket1 != null)
                    Socket1.Close();
            }
            catch { }
           
        }
        void TListient()
        {
            try
            {
                Socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//SERVER 1            
                Socket1.Bind(LocalIpPort);//SERVER 2
                Socket1.Listen(10);//SERVER 3
                ThreadWatch = new Thread(SWatch);
                ThreadWatch.IsBackground = true;
                ThreadWatch.Start();
                Common.AppendUiLog.Log("MPMS服务器监听成功...", LogType.Info);
            }
            catch
            {

            }
        }
        Socket Sock1;
        Thread threadMsg;
        bool IsWatch = true;
        void SWatch()
        {
            while (IsWatch)
            {
                Socket SocketReceive = Socket1.Accept();//SERVER 4
                Sock1 = SocketReceive;
                this.threadMsg = new Thread(RecMsg);
                this.threadMsg.IsBackground = true;
                this.threadMsg.Start();
                string IpKey = SocketReceive.RemoteEndPoint.ToString();
                Common.AppendUiLog.Log("MPMS客户端连接成功...", LogType.Info);
            }
        }

        byte[] cEndFlag = new byte[] { 0x0D, 0x0A };
        bool IsReceive = true;
        private void RecMsg()
        {
            try
            {
                List<byte> LstBytes = new List<byte>();
                while (IsReceive)
                {
                    byte[] buf = new byte[1024 * 1024 * 2];
                    int length = Sock1.Receive(buf, SocketFlags.Partial);
                    if (length > 0)
                    {
                        LstBytes.Clear();
                        for (int i = 0; i < length && i < buf.Length; i++)
                        {
                            bool IsEqual = true;
                            for (int j = 0; j < cEndFlag.Length; j++)
                            {
                                if (buf[i + j] != cEndFlag[j])
                                {
                                    IsEqual = false;
                                    break;
                                }
                            }
                            if (!IsEqual)
                                LstBytes.Add(buf[i]);
                            else
                            {
                                try
                                {
                                    byte[] LstRpc = cRcvEvent(LstBytes);
                                    Sock1.Send(LstRpc);
                                }
                                catch
                                {

                                }
                                break;
                            }
                        }
                    }
                }
            }
            catch
            {
                try
                {
                    CloseConnet();
                }
                catch
                {

                }
            }
        }
        public void CloseConnet()
        {
            Sock1.Close();
        }
    }
}
